package fu.capstone.hanoicityguide.presentation.fragment.attraction;

import java.util.HashMap;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.UtteranceProgressListener;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.facebook.UiLifecycleHelper;

import fu.capstone.hanoicityguide.R;
import fu.capstone.hanoicityguide.business.bo.attraction.AttractionBO;
import fu.capstone.hanoicityguide.business.bo.attraction.AttractionBOImp;
import fu.capstone.hanoicityguide.business.model.Attraction;
import fu.capstone.hanoicityguide.common.utility.InternetSetting;
import fu.capstone.hanoicityguide.common.utility.SharingFacebook;
import fu.capstone.hanoicityguide.presentation.adapter.ViewPagerAdapter;
import fu.capstone.hanoicityguide.presentation.fragment.home.HomeFragment;

;

@SuppressLint("ValidFragment")
public class DetailAttractionFragment extends Fragment implements
		OnInitListener {

	private AttractionBO attractionBO;
	private int attractionID;
	private ViewPager imgFragment;
	private ViewPagerAdapter vpagerAdapter;
	private TextToSpeech tts;
	private TextView attDescription;
	private TextView attInformation;
	private UiLifecycleHelper uiHelper;
	private InternetSetting internetSetting;
	private Button btnSpeak;
	private HashMap<String, String> utteranceHash;
	private UtteranceProgressListener utterance;

	public DetailAttractionFragment() {
	}

	public DetailAttractionFragment(int attractionID) {
		this.attractionID = attractionID;
	}

	public int getAttractionID() {
		return this.attractionID;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		if (tts != null) {
			tts.stop();
			tts.shutdown();
		}
		if (uiHelper != null) {
			uiHelper.onDestroy();
		}
		super.onDestroy();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// list attraction by filter and sorter
		View browseAttractionFragment = inflater.inflate(
				R.layout.fragment_detail_attraction, container, false);
		try {
			setHasOptionsMenu(true);
			internetSetting = new InternetSetting();
			utteranceHash = new HashMap<String, String>();

			tts = new TextToSpeech(getActivity(), this);

			attractionBO = new AttractionBOImp(container.getContext());

			// get data from database
			Attraction attraction = attractionBO
					.browseAttraction(getAttractionID());

			// fill data into components
			attDescription = (TextView) browseAttractionFragment
					.findViewById(R.id.txtAttDescription);
			attInformation = (TextView) browseAttractionFragment
					.findViewById(R.id.txtAttInformation);
			attDescription.setText(attraction.getDescription());

			String information = "";
			if (!"".equals(attraction.getAddress().trim())
					&& attraction.getAddress() != null) {
				information = information.concat("Address : ");
				information = information.concat(attraction.getAddress());
				information = information.concat("\n");
			}
			if (!"".equals(attraction.getPhoneNumber().trim())
					&& attraction.getPhoneNumber() != null) {
				information = information.concat("Phone number : ");
				information = information.concat(attraction.getPhoneNumber());
				information = information.concat("\n");
			}
			if (!"".equals(attraction.getWebsite().trim())
					&& attraction.getWebsite() != null) {
				information = information.concat("Website : ");
				information = information.concat(attraction.getWebsite());
				information = information.concat("\n");
			}

			if (!"".equals(attraction.getOpenTime().trim())
					&& !"".equals(attraction.getCloseTime())
					&& attraction.getOpenTime() != null
					&& attraction.getCloseTime() != null) {
				information = information.concat("Officehour : ");
				information = information.concat(attraction.getOpenTime());
				information = information.concat(" - ");
				information = information.concat(attraction.getCloseTime());
				information = information.concat("\n");
			}
			attInformation.setText(information);

			attraction.getArrImage();
			// FragmentActivity fma = (FragmentActivity) getActivity();

			imgFragment = (ViewPager) browseAttractionFragment
					.findViewById(R.id.attractionPager);

			vpagerAdapter = new ViewPagerAdapter(getActivity(),
					attraction.getArrImage());

			imgFragment.setAdapter(vpagerAdapter);

			btnSpeak = (Button) browseAttractionFragment
					.findViewById(R.id.btnSpeakOut);

			btnSpeak.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (tts.isSpeaking()) {
						btnSpeak.setText("Speak");
						tts.stop();
					} else {
						btnSpeak.setText("Stop");
						speakOut();
					}

				}
			});
		} catch (Exception e) {
			Log.e("Detail Attraction Fragment", e.toString());
		}

		return browseAttractionFragment;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// TODO Auto-generated method stub
		inflater = getActivity().getMenuInflater();
		inflater.inflate(R.menu.detailed_place_page_menu, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		Fragment fragment = new Fragment();
		internetSetting = new InternetSetting(getActivity());
		switch (item.getItemId()) {
		case R.id.action_map: {
			if (tts.isSpeaking()) {
				btnSpeak.setText("Speak");
				tts.stop();
				tts.shutdown();
				tts = null;
			}
			if (!internetSetting.getConnectivityStatus(getActivity())
					&& HomeFragment.isPurchased) {
				fragment = new AttractionOfflineMapFragment();
				Bundle bundle = new Bundle();
				bundle.putInt("AttractionID", attractionID);
				fragment.setArguments(bundle);
				if (fragment != null) {
					FragmentManager fragmentManager = getFragmentManager();
					FragmentTransaction fTransaction = fragmentManager
							.beginTransaction();
					fTransaction.addToBackStack(null);
					fTransaction.replace(R.id.frame_container, fragment)
							.commit();
					getActivity().setTitle("View on map");
				}
			}

			if (internetSetting.getConnectivityStatus(getActivity())) {
				fragment = new AttractionOnlineMapFragment();
				Bundle bundle = new Bundle();
				bundle.putInt("AttractionID", attractionID);
				fragment.setArguments(bundle);
				if (fragment != null) {
					FragmentManager fragmentManager = getFragmentManager();
					FragmentTransaction fTransaction = fragmentManager
							.beginTransaction();
					fTransaction.addToBackStack(null);
					fTransaction.replace(R.id.frame_container, fragment)
							.commit();
					getActivity().setTitle("View on map");
				}
			}

			if (!internetSetting.getConnectivityStatus(getActivity())
					&& !HomeFragment.isPurchased) {
				internetSetting.showSettingsAlert();
			}

		}
			break;
		case R.id.action_checkin: {

			if (!internetSetting.getConnectivityStatus(getActivity())) {
				internetSetting.showSettingsAlert();
			} else {
				uiHelper = new UiLifecycleHelper(getActivity(), null);
				SharingFacebook.shareFacebook(uiHelper, getActivity());
			}
		}
			break;
		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onInit(int status) {
		utteranceHash = new HashMap<String, String>();
		utteranceHash.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "done");
		utterance = new UtteranceProgressListener() {
			Handler handler = new Handler();
			String btnName = "Stop";
			Runnable runnable = new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					btnSpeak.setText(btnName);
				}
			};

			@Override
			public void onStart(String utteranceId) {
				// TODO Auto-generated method stub
				btnName = "Stop";
				handler.post(runnable);
			}

			@Override
			public void onError(String utteranceId) {
				// TODO Auto-generated method stub
				Log.v("Error Voice Guidance", "Error");
			}

			@Override
			public void onDone(String utteranceId) {
				// TODO Auto-generated method stub
				btnName = "Speak";
				handler.post(runnable);
			}
		};
		tts.setOnUtteranceProgressListener(utterance);
		if (status == TextToSpeech.SUCCESS) {

			int result = tts.setLanguage(Locale.US);

			if (result == TextToSpeech.LANG_MISSING_DATA
					|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
				Log.e("TTS", "This Language is not supported");
			} else {
				btnSpeak.setText("Stop");
				speakOut();
			}

		} else {
			Log.e("TTS", "Initilization Failed!");
		}
	}

	private void speakOut() {

		String text = attDescription.getText().toString();

		tts.speak(text, TextToSpeech.QUEUE_ADD, utteranceHash);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		getActivity().getActionBar().setTitle(
				attractionBO.browseAttraction(attractionID).getName());
	}

}
